<!--
 * @Description: 你的代码我的心
 * @Author: GGB
 * @Date: 2021-12-24 14:08:47
 * @LastEditors: GGB
 * @LastEditTime: 2022-01-22 15:43:05
-->
<template>
  <BasicModal v-bind="$attrs" @ok="handleOk" @register="register" title="更新库存" width="800px">
    <div class="container">
      <Description :column="4" :data="goods" v-show="goods.goods_image" :schema="descItemSchema" />
      <Table
        :pagination="false"
        :columns="columns"
        rowKey="id"
        :data-source="goods.skuList"
        bordered
      >
        <template #goods_props="{ text }">
          <span v-if="!text">单规格</span>
          <template v-else>
            {{ getSku(text) }}
          </template>
        </template>
        <template v-for="col in ['stock_num']" #[col]="{ text, record }" :key="col">
          <div>
            <a-input
              v-if="showEdit && editableData[record.id]"
              v-model:value="editableData[record.id][col]"
              style="margin: -5px 0"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template #operation="{ record }">
          <div class="editable-row-operations">
            <span v-if="showEdit && editableData[record.id]">
              <a @click="save(record.id)">保存</a>
              <Popconfirm title="是否确定取消" @confirm="cancel(record.id)">
                <a>取消</a>
              </Popconfirm>
            </span>
            <span v-else>
              <a @click="edit(record.id)">编辑</a>
            </span>
          </div>
        </template>
      </Table>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { reactive, ref, UnwrapRef } from 'vue';
  import { descItemSchema } from './modal.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Description } from '/@/components/Description/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { getGoodDetail, updateGoodsStock } from '/@/api/goods';
  import { GoodsItemModel, GoodsParams, UpdateStockParam } from '/@/api/goods/model/goodsModel';
  import { Table, Popconfirm } from 'ant-design-vue';
  import { cloneDeep } from 'lodash-es';

  const { createMessage } = useMessage();

  interface DataItem {
    goods_unit: string;
    stock_num: string;
    id: number | string;
    goods_id?: number | string;
    goods_sku_id?: number | string;
  }
  const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});
  // 弹框的数据记录
  const goods = ref<GoodsItemModel>({});
  const showEdit = ref(false);
  const columns = [
    {
      title: '规格SKU',
      dataIndex: 'goods_props',
      slots: { customRender: 'goods_props' },
      width: '20%',
      align: 'center',
    },
    {
      title: '单位',
      dataIndex: 'goods_unit',
      slots: { customRender: 'goods_unit' },
      width: '30%',
      align: 'center',
    },
    {
      title: '库存',
      dataIndex: 'stock_num',
      slots: { customRender: 'stock_num' },
      width: '30%',
      align: 'center',
    },
    {
      title: '修改',
      dataIndex: 'operation',
      slots: { customRender: 'operation' },
      width: '20%',
      align: 'center',
    },
  ];

  // 修改
  const edit = (key: number) => {
    showEdit.value = true;
    if (goods.value.skuList) {
      editableData[key] = cloneDeep(goods.value.skuList?.filter((item) => key === item.id)[0]);
    }
  };
  // 保存 TODO 留一个bug
  const save = (key: number) => {
    showEdit.value = false;
    Object.assign(goods.value.skuList?.filter((item) => key === item.id)[0], editableData[key]);
  };
  // 取消
  const cancel = (key: string) => {
    showEdit.value = false;
    delete editableData[key];
  };
  // 重新加载
  let reload = () => {};

  // 获取sku
  const getSku = (item) => {
    let { group, value } = item[0];
    return `${group.name}-${value.name}`;
  };

  const [register, { closeModal, changeOkLoading }] = useModalInner(async (data) => {
    // 拿到商品id
    const goodsId = data.record.goods_id;
    const { goodsInfo } = await getGoodDetail({ goodsId } as GoodsParams);
    goods.value = goodsInfo;
    reload = data.reload;
  });
  // 更新库存
  const handleOk = () => {
    let arr: any = [];
    // 拼接参数
    for (let key in editableData) {
      let { id, goods_sku_id, goods_id, stock_num } = editableData[key];
      arr.push({ id, goods_sku_id, goods_id, stock_num });
    }
    // 组合请求参数
    let params = {
      goodsId: goods.value.goods_id,
      form: {
        skuList: arr,
      },
    } as UpdateStockParam;
    changeOkLoading(true);
    updateGoodsStock(params)
      .then(({ status, message }) => {
        closeModal();
        // createMessage.success(res.message);
        status === 200 ? createMessage.success(message) : createMessage.error(message);
        reload();
      })
      .finally(() => changeOkLoading(false));
  };
</script>

<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 200px;
  }

  .editable-row-operations a {
    margin-right: 8px;
  }
</style>
